// 通信

// 发送当前页面统计
chrome.runtime.sendMessage({
  event: 'setReferer',
  data: window.location.href
});

let urls = [
  'https://www.etax-gd.gov.cn/',
  "https://etax.guangdong.chinatax.gov.cn/",
  "https://etax.beijing.chinatax.gov.cn/",

];
let ZDYpostMessage = (data, url = '*') => {
  data = JSON.stringify(data);
  window.postMessage(
    data,
    url
  );
};

// 长连接 与 background.js 通信
chrome.runtime.onConnect.addListener(function (port) {
  if (['toSaas', 'toInject', 'toWork'].includes(port.name)) {
    port.onMessage.addListener(function (data) {
      if (data.goType) {
        let href = window.location.href;
        if (urls.find(item => href.includes(item))) {
          let postMessageData = {
            event: data.event,
            sender: 'content-script',
            data: Object.assign({}, data.data)
          };
          ZDYpostMessage(postMessageData);
          return;
        }
        window.postMessage(
          {
            event: data.event,
            sender: 'content-script',
            data: Object.assign({}, data.data)
          },
          '*'
        );
      }
    });
  }
});
// 转化window postMessage 和 chrome.runtime.sendMessage
// message proxy
window.addEventListener(
  'message',
  function ({ data }) {
    let href = window.location.href;
    if (typeof data === 'string') {
      data = JSON.parse(data);
    }
    // 不监听自己给自己发的信息
    if (data.sender !== 'content-script' && data.event) {
      // todo 用长连接就不要用send message
      chrome.runtime.sendMessage(data, response => {
        if (response) {
          if (urls.find(item => href.includes(item))) {
            let postMessageData = Object.assign({}, response, {
              sender: 'content-script'
            });
            ZDYpostMessage(postMessageData);
            return;
          }
          window.postMessage(
            Object.assign({}, response, {
              sender: 'content-script'
            }),
            '*'
          );
        }
      });
    }
  },
  false
);
